﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Xml;
using System.Windows.Forms;
using SRCBQuestionnaireStatistic.Model;
using SRCBQuestionnaireStatistic.Command;
using System.IO;

namespace SRCBQuestionnaireStatistic
{
    public partial class MainForm : Form
    {
        private List<Questionnaire> availableQNs = new List<Questionnaire>();
        private QuestionnaireReader currentQNReader = null;
        private CommandStack cmdStack = new CommandStack();
        private string[] filenames = null;       // Added by Lex
        private string answersPath = @"\";                          // TODO: Configurable.
        private string answerFile = string.Empty;
        private string answerName = @"answers.xml";
        private int theIndexOfLastSurvey = 0;
        private int currentSurveyIndex = 0;
        private int selectedQNIndex = -1;

        private XmlDocument answersDocument = new XmlDocument();
        private XmlDocument statisticsDocument = new XmlDocument();

        public MainForm()
        {
            string currentDirectory = Directory.GetCurrentDirectory();
            string questionnairePath = Path.Combine(currentDirectory, "Resources");
            filenames = Directory.GetFiles(questionnairePath, "*.xml");
            InitializeComponent();
            SetMenuStatus(-1);
        }

        #region Events
        private void NewQuestionnaireToolStripMenuItem_Click(object sender, EventArgs e)
        {
            NewSurvey(answerFile, ++theIndexOfLastSurvey);
        }

        private void LoadQuestionnaires(string[] fileNames)
        {
            int index = 0;
            foreach (string filename in filenames)
            {
                Questionnaire qn = Questionnaire.MakeNew(filename);

                if (index == 0)
                    currentQNReader = new QuestionnaireReader(qn);
                availableQNs.Add(qn);
                index++;
            }
        }

        private string RetrieveDefaultOwner(int surveyIndex)
        {
            string defaultOwner = string.Empty;

            //this.treeView1.

            return defaultOwner;
        }

        private string BuildPath(int surveyIndex, string ownerName)
        {
            string path = string.Empty;

            path = Path.Combine("Resources", availableQNs[surveyIndex].Subject);

            if (availableQNs[surveyIndex].IsBranchManager)
            {
                path = Path.Combine(path, "Branches");
            }
            else if (availableQNs[surveyIndex].IsBossManager)
            {
                path = Path.Combine(path, "Headers");
            }
            else
            {
                // Nothing to do...
            }

            path = Path.Combine(path, ownerName);
            path = Path.Combine(path, SelectedYear.ToString());

            answersPath = path;
            path = Path.Combine(path, answerName);
            
            return path;
        }

        private void NewSurvey(string surveyPath, int surveyIndex)
        {
            theIndexOfLastSurvey = surveyIndex;
            currentSurveyIndex = theIndexOfLastSurvey;
            this.splitContainer2.Panel2.Controls.Clear();
            InitializeCustomizeComponent(selectedQNIndex, null);

            XmlElement questionnaire = Utility.AppendQuestionnarie(answersDocument);
            ShowTilteAndIndex();
            Utility.UpdateQuestionnaire(questionnaire, availableQNs[selectedQNIndex].Subject);

            foreach (Question q in availableQNs[selectedQNIndex].Questions)
            {
                XmlElement question = Utility.AppendQuestion(answersDocument);
                string content = q.Subject;
                string answer = "A";
                Utility.UpdateQuestion(question, content, answer);
            }

            answersDocument.Save(surveyPath);
        }

        private void LoadSurvey(string surveyPath)
        {
            answersDocument.Load(surveyPath);

            int count = answersDocument.GetElementsByTagName("questionnaire").Count;
            if (count > 0)
            {
                theIndexOfLastSurvey = count;
                
                DisplayAnswers(count);
            }
            else 
            {
                NewSurvey(surveyPath, 1);
            }

            currentSurveyIndex = theIndexOfLastSurvey;
            ShowTilteAndIndex();
        }

        private void ShowTilteAndIndex()
        {
            string title = Utility.RetrieveNodeByTagNameAndIndex(answersDocument, "title", 0).InnerText;
            int total = answersDocument.GetElementsByTagName("questionnaire").Count;

            this.labelQuestionnaireName.Text = "调研卷：" + title;
            this.labelQuestionnaireIndex.Text = "第[" + currentSurveyIndex.ToString() + "/" + total.ToString() + "]套";
        }

        private void ClearContextMenus()
        {
            this.treeView1.ContextMenu = null;
        }
        private void AddContextMenuAdd()
        {
            MenuItem menuAdd = new MenuItem("添加", TreeNodeClicked);
            menuAdd.Name = "MenuItemAdd";
            if (this.treeView1.ContextMenu == null)
                this.treeView1.ContextMenu = new ContextMenu();

            this.treeView1.ContextMenu.MenuItems.Add(menuAdd);
        }

        private void AddContextMenuEdit()
        {
            MenuItem menuEdit = new MenuItem("修改", TreeNodeClicked);
            menuEdit.Name = "MenuItemEdit";
            if (this.treeView1.ContextMenu == null)
                this.treeView1.ContextMenu = new ContextMenu();

            this.treeView1.ContextMenu.MenuItems.Add(menuEdit);
        }

        private void AddContextMenuDel()
        {
            MenuItem menuDel = new MenuItem("删除", TreeNodeClicked);
            menuDel.Name = "MenuItemDel";
            if (this.treeView1.ContextMenu == null)
                this.treeView1.ContextMenu = new ContextMenu();

            this.treeView1.ContextMenu.MenuItems.Add(menuDel);
        }
        private void MainForm_Load(object sender, EventArgs e)
        {
            this.Text = "上海农商银行问卷调查系统";
            ResetRightArea();

            InitialYearsToolStripMenuItem();
            LoadQuestionnaires(filenames);
            InitializeTreeView(availableQNs);
            this.MouseWheel += new MouseEventHandler(MainFrom_MouseWheel);

            TreeNode rootNode = treeView1.Nodes[0];
            foreach (TreeNode tn in rootNode.Nodes)
            {
                foreach (TreeNode tnFunc in tn.Nodes)
                {
                    if (tnFunc.Text == "支行管理" || tnFunc.Text == "领导管理")
                        RefreshTreeNode(tnFunc, SelectedYear);
                }
            }
        }

        private void InitialYearsToolStripMenuItem()
        {
            ToolStripMenuItem prev5yearStripMenuItem = new ToolStripMenuItem();
            prev5yearStripMenuItem.Name = "prev5yearStripMenuItem";
            prev5yearStripMenuItem.Text = string.Format("切换至前五年 {0}", DateTime.Now.Year - 5);
            prev5yearStripMenuItem.Click += new EventHandler(yearsStripMenuItem_Click);

            ToolStripMenuItem prev4yearStripMenuItem = new ToolStripMenuItem();
            prev4yearStripMenuItem.Name = "prev4yearStripMenuItem";
            prev4yearStripMenuItem.Text = string.Format("切换至前四年 {0}", DateTime.Now.Year - 4);
            prev4yearStripMenuItem.Click += new EventHandler(yearsStripMenuItem_Click);

            ToolStripMenuItem prev3yearStripMenuItem = new ToolStripMenuItem();
            prev3yearStripMenuItem.Name = "prev3yearStripMenuItem";
            prev3yearStripMenuItem.Text = string.Format("切换至前三年 {0}", DateTime.Now.Year - 3);
            prev3yearStripMenuItem.Click += new EventHandler(yearsStripMenuItem_Click);

            ToolStripMenuItem prev2yearStripMenuItem = new ToolStripMenuItem();
            prev2yearStripMenuItem.Name = "prev2yearStripMenuItem";
            prev2yearStripMenuItem.Text = string.Format("切换至前二年 {0}", DateTime.Now.Year - 2);
            prev2yearStripMenuItem.Click += new EventHandler(yearsStripMenuItem_Click);

            ToolStripMenuItem prev1yearStripMenuItem = new ToolStripMenuItem();
            prev1yearStripMenuItem.Name = "prev1yearStripMenuItem";
            prev1yearStripMenuItem.Text = string.Format("切换至前一年 {0}", DateTime.Now.Year - 1);
            prev1yearStripMenuItem.Click += new EventHandler(yearsStripMenuItem_Click);

            ToolStripMenuItem currentyearStripMenuItem = new ToolStripMenuItem();
            currentyearStripMenuItem.Name = "xxxx0currentyearStripMenuItem";
            currentyearStripMenuItem.Text = string.Format("切换至当前年 {0} **", DateTime.Now.Year);
            currentyearStripMenuItem.Click += new EventHandler(yearsStripMenuItem_Click);

            ToolStripMenuItem next1yearStripMenuItem = new ToolStripMenuItem();
            next1yearStripMenuItem.Name = "next1yearStripMenuItem";
            next1yearStripMenuItem.Text = string.Format("切换至下一年 {0}", DateTime.Now.Year + 1);
            next1yearStripMenuItem.Click += new EventHandler(yearsStripMenuItem_Click);

            ToolStripMenuItem next2yearStripMenuItem = new ToolStripMenuItem();
            next2yearStripMenuItem.Name = "next2yearStripMenuItem";
            next2yearStripMenuItem.Text = string.Format("切换至下两年 {0}", DateTime.Now.Year + 2);
            next2yearStripMenuItem.Click += new EventHandler(yearsStripMenuItem_Click);

            ToolStripMenuItem next3yearStripMenuItem = new ToolStripMenuItem();
            next3yearStripMenuItem.Name = "next3yearStripMenuItem";
            next3yearStripMenuItem.Text = string.Format("切换至下三年 {0}", DateTime.Now.Year + 3);
            next3yearStripMenuItem.Click += new EventHandler(yearsStripMenuItem_Click);

            ToolStripMenuItem next4yearStripMenuItem = new ToolStripMenuItem();
            next4yearStripMenuItem.Name = "next4yearStripMenuItem";
            next4yearStripMenuItem.Text = string.Format("切换至下四年 {0}", DateTime.Now.Year + 4);
            next4yearStripMenuItem.Click += new EventHandler(yearsStripMenuItem_Click);

            ToolStripMenuItem next5yearStripMenuItem = new ToolStripMenuItem();
            next5yearStripMenuItem.Name = "next5yearStripMenuItem";
            next5yearStripMenuItem.Text = string.Format("切换至下五年 {0}", DateTime.Now.Year + 5);
            next5yearStripMenuItem.Click += new EventHandler(yearsStripMenuItem_Click);

            SwitchYearToolStripMenuItem1.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
            //EditToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
                prev5yearStripMenuItem,
                prev4yearStripMenuItem,
                prev3yearStripMenuItem,
                prev2yearStripMenuItem,
                prev1yearStripMenuItem,
                currentyearStripMenuItem,
                next1yearStripMenuItem,
                next2yearStripMenuItem,
                next3yearStripMenuItem,
                next4yearStripMenuItem,
                next5yearStripMenuItem
            });

            SelectedYear = DateTime.Now.Year;
            this.lblCurrentYear.Text = string.Format("当前您选中的是 {0} 年", SelectedYear);
        }
        private void yearsStripMenuItem_Click(object sender, EventArgs e)
        {
            string name = ((ToolStripMenuItem)sender).Name;
            if (name.StartsWith("next"))
            {
                int i = int.Parse(name.Substring(4, 1));
                SelectedYear = DateTime.Now.Year + i;
            }
            else
            {
                int i = int.Parse(name.Substring(4, 1));
                SelectedYear = DateTime.Now.Year - i;
            }
            TreeNode rootNode = treeView1.Nodes[0];
            foreach (TreeNode tn in rootNode.Nodes)
            {
                foreach (TreeNode tnFunc in tn.Nodes)
                {
                    if (tnFunc.Text == "支行管理" || tnFunc.Text == "领导管理")
                        RefreshTreeNode(tnFunc, SelectedYear);
                }
            }
            this.splitContainer2.Panel2.Controls.Clear();
            ResetRightArea();
            this.lblCurrentYear.Text = string.Format("当前您选中的是 {0} 年", SelectedYear);
            this.treeView1.SelectedNode = null;
            SetMenuStatus(-1);
        }

        private void ResetRightArea()
        {
            this.Previous.Enabled = false;
            this.Next.Enabled = false;
            this.labelQuestionnaireName.Text = "欢迎使用上海农商银行调研问卷系统";
            this.labelQuestionnaireIndex.Text = string.Empty;
        }
        private void TreeNodeClicked(object sender, EventArgs e)
        {
            MenuItem menuItem = (MenuItem)sender;
            switch (menuItem.Name)
            {
                case "MenuItemAdd":
                    if (treeView1.SelectedNode.Text == "支行管理" ||
                        treeView1.SelectedNode.Parent.Text == "支行管理")
                        AddBranch();
                    else
                        AddHeader();
                    break;
                case "MenuItemEdit":
                    if (treeView1.SelectedNode.Text == "支行管理" ||
                        treeView1.SelectedNode.Parent.Text == "支行管理")
                        EditBranch();
                    else
                        EditHeader();
                    break;
                case "MenuItemDel":
                    if (treeView1.SelectedNode.Text == "支行管理" ||
                        treeView1.SelectedNode.Parent.Text == "支行管理")
                        DeleteBranch();
                    else
                        DeleteHeader();
                    break;
                default:
                    throw new NotSupportedException(string.Format("Not supported {0}...", menuItem.Name));
            }
        }

        private void DeleteHeader()
        {
            string headerName = this.treeView1.SelectedNode.Text;
            string questionnaireName = this.treeView1.SelectedNode.Parent.Parent.Text;
            string fullPath = Path.Combine(Path.Combine(Path.Combine("Resources", questionnaireName), "Headers"), headerName);
            DirectoryInfo dir = new DirectoryInfo(fullPath);

            DialogResult result = 
                MessageBox.Show("确认删除该领导所属的所有问卷么？该操作不可逆！请您再次确认！！", "提示", MessageBoxButtons.OKCancel);

            if (result == DialogResult.OK)
            {
                try
                {
                    dir.Delete(true);
                }
                catch (IOException)
                {
                    MessageBox.Show(string.Format("请检查并关闭打开的文件夹 {0}，该文件夹内容已被强制删除！", fullPath));
                }
                RefreshTreeNode(treeView1.SelectedNode.Parent, SelectedYear);
                this.splitContainer2.Panel2.Controls.Clear();
                ResetRightArea();
                SetMenuStatus(-1);
            }
            else
            {
                // do nothing...
            }
        }

        private void DeleteBranch()
        {
            string branchName = this.treeView1.SelectedNode.Text;
            string questionnaireName = this.treeView1.SelectedNode.Parent.Parent.Text;
            string fullPath = Path.Combine(Path.Combine(Path.Combine("Resources", questionnaireName), "Branches"), branchName);
            DirectoryInfo dir = new DirectoryInfo(fullPath);

            DialogResult result =
                MessageBox.Show("确认删除该支行所属的所有问卷么？该操作不可逆！请您再次确认！！", "提示", MessageBoxButtons.OKCancel);

            if (result == DialogResult.OK)
            {
                try
                {
                    dir.Delete(true);
                }
                catch (IOException)
                {
                    MessageBox.Show(string.Format("请检查并关闭打开的文件夹 {0}，该文件夹内容将被强制删除！操作不可逆，请确认！", fullPath));
                }
                RefreshTreeNode(treeView1.SelectedNode.Parent, SelectedYear);
                this.splitContainer2.Panel2.Controls.Clear();
                ResetRightArea();
                SetMenuStatus(-1);
            }
            else
            {
                // do nothing
            }
        }

        private void EditHeader()
        {
            string newHeaderName = Prompt.ShowDialog("填写领导名称", "请输入");
            if (!Prompt.CurrentOpeningForm_UserClickedOKButton)
                return;

            string headerName = this.treeView1.SelectedNode.Text;
            string questionnaireName = this.treeView1.SelectedNode.Parent.Parent.Text;
            string fullPath = Path.Combine(Path.Combine(Path.Combine("Resources", questionnaireName), "Headers"), headerName);
            DirectoryInfo dir = new DirectoryInfo(fullPath);
            string newDir = string.Empty;
            try
            {
                newDir = Path.Combine(fullPath.Substring(0, fullPath.LastIndexOf('\\')), newHeaderName);
                dir.MoveTo(newDir);
            }
            catch (IOException)
            {
                MessageBox.Show(string.Format("请检查并关闭打开的文件夹 {0}", fullPath));
            }

            if (!string.IsNullOrEmpty(newDir))
            {
                string yearPath = Path.Combine(newDir, SelectedYear.ToString());
                answerFile = Path.Combine(yearPath, "answers.xml");

                answersDocument.Load(answerFile);
                answersDocument["survey"]["owner"].InnerText = newHeaderName;
                answersDocument.Save(answerFile);
                answersDocument.Load(answerFile);
            }

            RefreshTreeNode(treeView1.SelectedNode.Parent, SelectedYear);
        }

        private void EditBranch()
        {
            string newBranchName = Prompt.ShowDialog("填写支行名称", "请输入");
            if (!Prompt.CurrentOpeningForm_UserClickedOKButton)
                return;

            string branchName = this.treeView1.SelectedNode.Text;
            string questionnaireName = this.treeView1.SelectedNode.Parent.Parent.Text;
            string fullPath = Path.Combine(Path.Combine(Path.Combine("Resources", questionnaireName), "Branches"), branchName);
            string newDir = string.Empty;
            DirectoryInfo dir = new DirectoryInfo(fullPath);
            try
            {
                newDir = Path.Combine(fullPath.Substring(0, fullPath.LastIndexOf('\\')), newBranchName);
                dir.MoveTo(newDir);
            }
            catch (IOException)
            {
                MessageBox.Show(string.Format("请检查并关闭打开的文件夹 {0}", fullPath));
            }

            if (!string.IsNullOrEmpty(newDir))
            {
                string yearPath = Path.Combine(newDir, SelectedYear.ToString());
                answerFile = Path.Combine(yearPath, "answers.xml");
                
                answersDocument.Load(answerFile);
                answersDocument["survey"]["owner"].InnerText = newBranchName;
                answersDocument.Save(answerFile);
                answersDocument.Load(answerFile);
            }

            RefreshTreeNode(treeView1.SelectedNode.Parent, SelectedYear);
        }

        private void AddHeader()
        {
            string questionnaireName = this.treeView1.SelectedNode.Parent.Text;
            string headerName = Prompt.ShowDialog("填写领导名称", "请输入");
            if (!Prompt.CurrentOpeningForm_UserClickedOKButton)
                return;

            if (!string.IsNullOrEmpty(headerName))
            {
                if (!Directory.Exists("Resources"))
                    Directory.CreateDirectory("Resources");

                string path1 = Path.Combine("Resources", questionnaireName);
                if (!Directory.Exists(path1))
                    Directory.CreateDirectory(path1);

                string path2 = Path.Combine(path1, "Headers");
                if (!Directory.Exists(path2))
                    Directory.CreateDirectory(path2);

                string path3 = Path.Combine(path2, headerName);
                if (!Directory.Exists(path3))
                    Directory.CreateDirectory(path3);

                string path4 = Path.Combine(path3, SelectedYear.ToString());
                if (!Directory.Exists(path4))
                {
                    Directory.CreateDirectory(path4);
                    string filePath = Path.Combine(path4, answerName);
                    Utility.GenerateAnswers(filePath);
                    answersDocument.Load(filePath);
                    Utility.UpdateSurvey(answersDocument, selectedQNIndex.ToString(), headerName, questionnaireName);
                    answersDocument.Save(filePath);
                }
                else
                {
                    MessageBox.Show(string.Format("已存在{0}, 请重新填写名字", headerName));
                }

                RefreshTreeNode(treeView1.SelectedNode, SelectedYear);
                this.splitContainer2.Panel2.Controls.Clear();
                ResetRightArea();
            }
        }

        private int SelectedYear; 

        private void AddBranch()
        {
            string questionnaireName = this.treeView1.SelectedNode.Parent.Text;
            string branchName = Prompt.ShowDialog("填写支行名称", "请输入");
            if (!Prompt.CurrentOpeningForm_UserClickedOKButton)
                return;

            if (!string.IsNullOrEmpty(branchName))
            {
                if (!Directory.Exists("Resources"))
                    Directory.CreateDirectory("Resources");

                string path1 = Path.Combine("Resources", questionnaireName);
                if (!Directory.Exists(path1))
                    Directory.CreateDirectory(path1);

                string path2 = Path.Combine(path1, "Branches");
                if (!Directory.Exists(path2))
                    Directory.CreateDirectory(path2);

                string path3 = Path.Combine(path2, branchName);
                if (!Directory.Exists(path3))
                    Directory.CreateDirectory(path3);

                string path4 = Path.Combine(path3, SelectedYear.ToString());
                if (!Directory.Exists(path4))
                {
                    Directory.CreateDirectory(path4);
                    string filePath = Path.Combine(path4, answerName);
                    Utility.GenerateAnswers(filePath);
                    answersDocument.Load(filePath);
                    Utility.UpdateSurvey(answersDocument, selectedQNIndex.ToString(), branchName, questionnaireName);
                    answersDocument.Save(filePath);
                }
                else
                {
                    MessageBox.Show(string.Format("已存在{0}, 请重新填写名字", branchName));
                }


                RefreshTreeNode(treeView1.SelectedNode, SelectedYear);
                this.splitContainer2.Panel2.Controls.Clear();
                ResetRightArea();
            }
        }

        /// <summary>
        /// RefreshTreeNode
        /// </summary>
        /// <param name="rootNode"></param>
        /// <param name="nodeFn">nodeFn must be the node whose text like "支行管理" or "领导管理"</param>
        private static void RefreshTreeNode(TreeNode nodeFn, int selectedYear)
        {
            TreeNode rootNode = nodeFn.Parent.Parent.Parent;
            //foreach (TreeNode tn in rootNode.Nodes)
            {
                string questionnaireName = nodeFn.Parent.Text;
                DirectoryInfo dirResources = new DirectoryInfo("Resources");
                DirectoryInfo[] dirs = null;
                if (nodeFn.Text == "支行管理")
                {
                    string branchesSubFolder = Path.Combine(questionnaireName, @"Branches\");
                    if (Directory.Exists(Path.Combine(dirResources.Name, branchesSubFolder)))
                        dirs = dirResources.GetDirectories(branchesSubFolder);
                }
                else if (nodeFn.Text == "领导管理")
                {
                    string headersSubFolder = Path.Combine(questionnaireName, @"Headers\");
                    if (Directory.Exists(Path.Combine(dirResources.Name, headersSubFolder)))
                        dirs = dirResources.GetDirectories(headersSubFolder);
                }

                if (dirs != null)
                {
                    // Adds the new node.
                    // Loops the dir, find the branch/header exists in dir, but not in tree, then added them.
                    foreach (DirectoryInfo dir in dirs)
                    {
                        bool existing = false;
                        foreach (TreeNode existingTN in nodeFn.Nodes)
                        {
                            // Name exists, and the subfolder contains the selected year.
                            if (existingTN.Text == dir.Name)
                                existing = true;
                        }
                        bool containsSelectedYear = false;
                        DirectoryInfo[] yearsFolder = dir.GetDirectories();
                        foreach (DirectoryInfo year in yearsFolder)
                        {
                            if (year.Name == selectedYear.ToString())
                            {
                                containsSelectedYear = true;
                                break;
                            }
                        }

                        if (!existing && containsSelectedYear)
                            nodeFn.Nodes.Add("header_" + dir.Name, dir.Name);
                       
                    }

                    // Removes the nodes no longer exists.
                    // Loops the tree, find the branch/header exists in tree, but not in dir, then removed them.
                    //int index = -1;
                    for (int index = nodeFn.Nodes.Count - 1; index >= 0; index--)
                    {
                        TreeNode existingTN = nodeFn.Nodes[index];
                        bool existing = false;
                        foreach (DirectoryInfo dir in dirs)
                        {
                            bool containsSelectedYear = false;
                            DirectoryInfo[] yearsFolder = dir.GetDirectories();
                            foreach (DirectoryInfo year in yearsFolder)
                            {
                                if (year.Name == selectedYear.ToString())
                                {
                                    containsSelectedYear = true;
                                    break;
                                }
                            }

                            if (dir.Name == existingTN.Text && containsSelectedYear)
                                existing = true;
                        }
                        if (!existing)
                            nodeFn.Nodes.RemoveAt(index);
                    }
                    //foreach (TreeNode existingTN in nodeFn.Nodes)
                    //{
                    //    //index++;
                    //    bool existing = false;
                    //    foreach (DirectoryInfo dir in dirs)
                    //    {
                    //        bool containsSelectedYear = false;
                    //        DirectoryInfo[] yearsFolder = dir.GetDirectories();
                    //        foreach (DirectoryInfo year in yearsFolder)
                    //        {
                    //            if (year.Name == selectedYear.ToString())
                    //            {
                    //                containsSelectedYear = true;
                    //                break;
                    //            }
                    //        }

                    //        if (dir.Name == existingTN.Text && containsSelectedYear)
                    //            existing = true;
                    //    }
                    //    if (!existing)
                    //        nodeFn.Nodes.Remove(existingTN);
                    //}
                    nodeFn.ExpandAll();
                }
            }
        }
        private void MainFrom_MouseWheel(object sender, MouseEventArgs e)
        {
            Point mousePoint = new Point(e.X, e.Y);

            mousePoint.Offset(this.Location.X, this.Location.Y);
            SplitterPanel panel = this.splitContainer2.Panel2;

            if (panel.RectangleToScreen(panel.DisplayRectangle).Contains(mousePoint))
            {
                panel.AutoScrollPosition = new Point(0, panel.VerticalScroll.Value - e.Delta);
            }
        }

        private void statistics(string path, string selectedRole)
        {
            bool all = false;
            Utility.GenerateStatistics(path);
            statisticsDocument.Load(path);
            
            answersDocument.Load(answerFile);
            
            Utility.UpdateStatistic(statisticsDocument,
                answersDocument["survey"]["index"].InnerText,
                answersDocument["survey"]["owner"].InnerText,
                SelectedYear.ToString(),
                answersDocument["survey"]["title"].InnerText);

            string selectedOption = "A"; // Default value is "A".
            if (!string.IsNullOrEmpty(selectedRole))
            {
                if (string.Equals(selectedRole, StatisticBasisPrompt.AllClicked))
                {
                    all = true;
                }
                else
                {
                    selectedOption = selectedRole.Substring(0, 1);
                    statisticsDocument["statistics"]["role"].InnerText = selectedRole.Substring(3, selectedRole.Length - 3);
                }
            }

            
            XmlNodeList questionnaires = answersDocument.GetElementsByTagName("questionnaire");
            int surveyIndex = int.Parse(answersDocument["survey"]["index"].InnerText);
            List<string> qIndexList = new List<string>();

            int realIndex = 0;
            int surveyCount = 0;
            foreach (XmlElement questionnaire in questionnaires)
            {
                XmlNodeList questions = questionnaire.GetElementsByTagName("question");

                XmlNode roleQuestion = questions[0];

                if (surveyIndex == 2)
                {
                    string role = roleQuestion["answer"].InnerText.Trim();

                    if (!all)
                    {
                        if (!string.Equals(role, selectedOption))
                        {
                            continue;
                        }
                    }
                }

                surveyCount++;

                foreach (XmlElement question in questions)
                {
                    string qIndex = question["qIndex"].InnerText;

                    int questionIndex = int.Parse(qIndex);
                    if (surveyIndex == 2)
                    {
                        if (questionIndex <= 3)
                        {
                            continue;
                        }
                        else
                        {
                            realIndex = questionIndex;
                            questionIndex -= 3;
                            qIndex = questionIndex.ToString();
                        }
                    }
                    else
                    {
                        realIndex = questionIndex;
                    }

                    string answer = question["answer"].InnerText;
                    string[] answers = answer.Split(',');
                    bool newAQuestionNodex = false;

                    if (!qIndexList.Contains(qIndex))
                    {
                        newAQuestionNodex = true;
                        qIndexList.Add(qIndex);
                    }

                    XmlElement statisticQuestion = null;

                    if (newAQuestionNodex)
                    {
                        int index = realIndex;
                        index--;

                        Question currentQuestion = availableQNs[surveyIndex].Questions[index];

                        AnswerList answerList = availableQNs[surveyIndex].Questions[index].AvailableAnswers;
                        int count = answerList.Count;
                        string[] newSyms = new string[count];
                        string[] newTexts = new string[count];
                        for (int answerIndex = 0; answerIndex < count; answerIndex++)
                        {
                            newSyms[answerIndex] = answerList[answerIndex].Sym.ToString().Trim();
                            newTexts[answerIndex] = answerList[answerIndex].Text.ToString().Trim();
                        }

                        statisticQuestion = Utility.AppendStatisticsQuestion(statisticsDocument, newSyms);

                        Utility.AddStatisticsColumns(statisticsDocument, newSyms, newTexts);

                        statisticQuestion["type"].InnerText = availableQNs[surveyIndex].Questions[index].QuestionType.ToString();
                    }
                    else
                    {
                        XmlNodeList questionList = statisticsDocument.GetElementsByTagName("sQuestion");
                        int index = int.Parse(qIndex);
                        if (index > 0)
                        {
                            index--;
                        }
                        statisticQuestion = (XmlElement)questionList[index];
                    }

                    statisticQuestion = Utility.AppendAnswer(statisticsDocument, statisticQuestion, answers);

                    if (statisticQuestion != null)
                    {
                        Utility.UpdateStatisticQuestion(statisticQuestion, qIndex, answers);
                    }

                }
            }

            // Fill answers up if this is the 3rd survey.
            if (int.Parse(statisticsDocument["statistics"]["index"].InnerText) == 2)
            {
                Utility.FillAnswersUp(statisticsDocument, "N/A");
            }

            // Fill total
            statisticsDocument["statistics"]["total"].InnerText = surveyCount.ToString();

            statisticsDocument.Save(path);
        }

        private void StatisticToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string selected = string.Empty;

            if (availableQNs[selectedQNIndex].ContainsStatisticBasisQuestions())
            {
                selected = StatisticBasisPrompt.ShowDialog(availableQNs[selectedQNIndex].GetStatisticBasisQuestions(), "分类统计项", "请选择分类统计项", 900, 180);
                selected = selected.Replace(StatisticBasisPrompt.OkClicked, string.Empty).TrimEnd(new char[] { ';', ' ' });
            }
            if (!string.IsNullOrEmpty(selected) || !availableQNs[selectedQNIndex].ContainsStatisticBasisQuestions())
            {
                string answerFileDirectory = Path.GetDirectoryName(answerFile);
                string statisticsPath = Path.Combine(answerFileDirectory, "statistics.xml");

                statistics(statisticsPath, selected);
                System.Diagnostics.Process.Start("IEXPLORE.EXE", Path.Combine(Environment.CurrentDirectory, statisticsPath));
            }
        }

        private void UndoToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (cmdStack.Count <= 0)
            {
                MessageBox.Show("没有上一题了！");
                return;
            }
            FillAnswerCommand cmd = (FillAnswerCommand)cmdStack.Pop();
            cmd.Undo();
            currentQNReader.SetIndex(cmd.Question.Index);
            PopulateQuestionUI(cmd.Question);
        }

        private void FillAnswerToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (currentQNReader.ReadNext())
            {
                PopulateQuestionUI(currentQNReader.Question);
            }
        }

        private void MainForm_KeyPress(object sender, KeyPressEventArgs e)
        {
            int index = -1;
            if (int.TryParse(e.KeyChar.ToString(), out index))
            {
                index = index - 1;
            }
            else
            {
                index = Utility.ConvertToIndex(e.KeyChar.ToString());
            }

            if (index < 0)
                return;

            foreach (Control radio in respondingPanel.Controls)
            {
                if (radio is RadioButton ||
                    radio is CheckBox)
                {
                    if (radio is RadioButton) // Single choice
                    {
                        string radioName = radio.Name;
                        int questionIndex = int.Parse(radioName.Split('.')[1]);
                        int answerIndex = int.Parse(radioName.Split('.')[2]);
                        if (answerIndex == index)
                        {
                            ((RadioButton)radio).Checked = true;
                            ((RadioButton)radio).Focus();
                            FillAnswerByQuestion(questionIndex, new List<int>() { answerIndex });
                            //((RadioButton)radio).SelectNextControl(
                            break;
                        }
                    }
                    else if (radio is CheckBox)
                    {
                        string radioName = radio.Name;
                        int questionIndex = int.Parse(radioName.Split('.')[1]);
                        int answerIndex = int.Parse(radioName.Split('.')[2]);
                        if (answerIndex == index)
                        {
                            ((CheckBox)radio).Checked = !((CheckBox)radio).Checked;
                            ((CheckBox)radio).Focus();

                            Panel questionPanel = (Panel)radio.Parent;
                            List<int> multiAnswers = new List<int>();

                            foreach (Control ctl in questionPanel.Controls)
                            {
                                if (ctl.Name.StartsWith("answer"))
                                {
                                    CheckBox answerCheck = (CheckBox)ctl;
                                    if (answerCheck.Checked)
                                    {
                                        radioName = answerCheck.Name;
                                        multiAnswers.Add(int.Parse(radioName.Split('.')[2]));
                                    }
                                }
                            }

                            FillAnswerByQuestion(questionIndex, multiAnswers);
                            break;
                        }
                    }
                }
            }
        }

        private void SetSelectedNodeIndex(TreeNode selectedNode)
        {
            TreeNode node = selectedNode;
            while (node.Level != 1)
            {
                node = node.Parent;
            }

            if (node.Level == 1)
            {
                foreach (Questionnaire qn in availableQNs)
                {
                    if (string.Equals(node.Text, qn.Subject))
                    {
                        selectedQNIndex = qn.Index;
                        break;
                    }
                }
            }
        }

        private void treeView1_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            this.Previous.Enabled = true;
            this.Next.Enabled = true;

            this.treeView1.SelectedNode = e.Node;
            int currentNodeIndex = selectedQNIndex;
            // Check which kind of node is selected. ==>
            bool isRootNodeSelected = false;
            bool isQnNodeSelected = false;
            bool isFnNodeSelected = false;
            bool isLeafNodeSelected = false;

            SetMenuStatus(this.treeView1.SelectedNode.Level);
            isRootNodeSelected = e.Node.Parent == null;
            if (!isRootNodeSelected)
            {
                isQnNodeSelected = e.Node.Parent.Parent == null;
                if (!isQnNodeSelected)
                {
                    isFnNodeSelected = e.Node.Parent.Parent.Parent == null;
                    if (!isFnNodeSelected)
                        isLeafNodeSelected = e.Node.Parent.Parent.Parent.Parent == null;
                }
            }
            // <==

            // Add Context Menus ==>
            ClearContextMenus();
            if (isFnNodeSelected || isLeafNodeSelected)
            {
                if (this.treeView1.SelectedNode.Text == "支行管理" ||
                    this.treeView1.SelectedNode.Text == "领导管理")
                {
                    AddContextMenuAdd();
                }
                else if (this.treeView1.SelectedNode.Parent.Text == "支行管理" ||
                    this.treeView1.SelectedNode.Parent.Text == "领导管理")
                {
                    AddContextMenuEdit();
                    AddContextMenuDel();
                }
                else
                {
                    // nothing to do...
                }
            }
            // <==

            if (isRootNodeSelected && e.Button == System.Windows.Forms.MouseButtons.Left)
            {
                TreeNode tnLeaf = null;
                if (e.Node.Nodes[0].Nodes[0].Nodes != null &&
                    e.Node.Nodes[0].Nodes[0].Nodes.Count > 0)
                {
                    tnLeaf = e.Node.Nodes[0].Nodes[0].Nodes[0];
                    GotoFirstLeafQuestionnaire(tnLeaf);
                }
                this.ResetRightArea();
                this.splitContainer2.Panel2.Controls.Clear();
                return;
            }
            else if (isQnNodeSelected && e.Button == System.Windows.Forms.MouseButtons.Left)
            {
                TreeNode tnLeaf = null;
                if (e.Node.Nodes[0].Nodes != null &&
                    e.Node.Nodes[0].Nodes.Count > 0)
                {
                    tnLeaf = e.Node.Nodes[0].Nodes[0];
                    GotoFirstLeafQuestionnaire(tnLeaf);
                }
                this.ResetRightArea();
                this.splitContainer2.Panel2.Controls.Clear();
                return;
            }
            else if (isFnNodeSelected && e.Button == System.Windows.Forms.MouseButtons.Left)
            {
                TreeNode tnLeaf = null;
                if (e.Node.Nodes != null &&
                    e.Node.Nodes.Count > 0)
                {
                    tnLeaf = e.Node.Nodes[0];
                    GotoFirstLeafQuestionnaire(tnLeaf);
                }
                this.ResetRightArea();
                this.splitContainer2.Panel2.Controls.Clear();
                return;
            }

            // Display the questionnaire on the right panel.
            // The tree structure is fixed so use Parent.Parent shouldn't be an issue.
            SetSelectedNodeIndex(this.treeView1.SelectedNode);
            if (this.treeView1.SelectedNode.Parent.Parent != null)
            {
                string selectedNodeText = this.treeView1.SelectedNode.Parent.Parent.Text;
                int qnIndex = 0;
                foreach (Questionnaire qn in availableQNs)
                {
                    if (string.Equals(qn.Subject, selectedNodeText))
                    {
                        answerFile = BuildPath(qnIndex, this.treeView1.SelectedNode.Text);
                        LoadSurvey(answerFile);

                        break;
                    }

                    qnIndex++;
                }
            }
        }

        private void GotoFirstLeafQuestionnaire(TreeNode tnLeaf)
        {
            //treeView1.HideSelection = false;
            //treeView1.SelectedNode = tnLeaf;
            //treeView1.Focus();
            //MessageBox.Show(tnLeaf.Text);
        }

        private void ExitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        #endregion

        #region Methods

        private void SetMenuStatus(int nodeLevel)
        {
            if (nodeLevel == 3) // Branches or Headers
            {
                NewQuestionnaireToolStripMenuItem.Enabled = true;
                StatisticToolStripMenuItem.Enabled = true;
                NextQNToolStripMenuItem.Enabled = true;
                PrevQNToolStripMenuItem.Enabled = true;
            }
            else
            {
                NewQuestionnaireToolStripMenuItem.Enabled = false;
                StatisticToolStripMenuItem.Enabled = false;
                NextQNToolStripMenuItem.Enabled = false;
                PrevQNToolStripMenuItem.Enabled = false;
            }
        }

        private void InitializeTreeView(List<Questionnaire> qns)
        {
            treeView1.Nodes.Clear();
            TreeNode rootNode = treeView1.Nodes.Add("rootNode", "农商银行问卷调查统计系统");
            foreach (Questionnaire qn in qns)
            {
                TreeNode nodeQN = rootNode.Nodes.Add("qn_node_" + qn.Id, qn.Subject);

                if (qn.IsBossManager)
                    nodeQN.Nodes.Add("menu_node_" + qn.Id + "_BossManager", "领导管理");
                if (qn.IsBranchManager)
                    nodeQN.Nodes.Add("menu_node_" + qn.Id + "_BranchManager", "支行管理");
            }

            treeView1.ExpandAll();
            treeView1.SelectedNode = treeView1.Nodes[0].Nodes[0];
        }

        private void FillAnswerByQuestion(int questionIndex, List<int> answerList)
        {
            int sureyIndex = currentSurveyIndex - 1;
            answersDocument.Load(answerFile);
            XmlNode currentSurvey = Utility.RetrieveNodeByTagNameAndIndex(answersDocument, "questionnaire", sureyIndex);
            XmlNode currentQuestion = Utility.RetrieveNodeByTagNameAndIndex2((XmlElement)currentSurvey, "question", questionIndex);

            string answerToFill = string.Empty;
            if (answerList.Count == 1)
            {
                answerToFill = Utility.ConvertToSymbol(answerList[0]).ToString();
                
            }
            else
            {
                StringBuilder answersBuilder = new StringBuilder();
                foreach (int answer in answerList)
                {
                    answersBuilder.Append(Utility.ConvertToSymbol(answer).ToString());
                    answersBuilder.Append(",");
                }

                if (answersBuilder.Length > 1)
                {
                    answersBuilder = answersBuilder.Remove(answersBuilder.Length - 1, 1);
                }
                answerToFill = answersBuilder.ToString();
            }

            Utility.UpdateQuestion((XmlElement)currentQuestion, string.Empty, answerToFill);
            answersDocument.Save(answerFile);
        }

        private void PopulateQuestionUI(Question q)
        {
            int questionIndex = currentQNReader.CurrentIndex + 1;
            this.labelQuestionnaireIndex.Text = string.Format("当前为第 [{0}] 份调研卷中的第 [{1}] 道问题", currentSurveyIndex.ToString(), questionIndex.ToString());
            labelQuestionnaireName.Text = q.Questionnaire.Subject;

            object[] list = new object[q.AvailableAnswers.Count];
            for (int i = 0; i < q.AvailableAnswers.Count; i++)
            {
                list[i] = q.AvailableAnswers[i];
            }
        }

        #endregion      

        private void Next_Click(object sender, EventArgs e)
        {
            if (currentSurveyIndex == theIndexOfLastSurvey)
            {
                DialogResult dr = MessageBox.Show("当前为最后一份调研卷。 是否要创建新的调研卷？ ", "提示", MessageBoxButtons.OKCancel);

                if (dr == System.Windows.Forms.DialogResult.OK)
                {
                    NewSurvey(answerFile, ++theIndexOfLastSurvey);
                }
                else
                {
                    // nothing to do...
                }
            }
            else if (currentSurveyIndex < theIndexOfLastSurvey)
            {
                DisplayAnswers(++currentSurveyIndex);
            }
            else
            {
                // Nothing to do.
            }
        }

        private void Previous_Click(object sender, EventArgs e)
        {
            if (currentSurveyIndex == 1)
            {
                MessageBox.Show("当前为第一份调研卷，没有上一份了。");
            }
            else
            {
                DisplayAnswers(--currentSurveyIndex);
            }
        }

        private void splitContainer2_Panel2_MouseDown(object sender, MouseEventArgs e)
        {
            this.splitContainer2.Panel2.Focus();
        }

        private void answerRadio_CheckedChanged(object sender, EventArgs e)
        {
            RadioButton clickedRadio = (RadioButton)sender;
            string radioName = clickedRadio.Name;
            int questionIndex = int.Parse(radioName.Split('.')[1]);
            int answerIndex = int.Parse(radioName.Split('.')[2]);

            List<int> singleAnswer = new List<int>();
            singleAnswer.Add(answerIndex);
            FillAnswerByQuestion(questionIndex, singleAnswer);
        }

        private void answerCheckbox_CheckedChanged(object sender, EventArgs e)
        {
            CheckBox clickedCheck = (CheckBox)sender;

            string checkboxName = clickedCheck.Name;
            int questionIndex = int.Parse(checkboxName.Split('.')[1]);

            Panel questionPanel = (Panel)clickedCheck.Parent;
            List<int> multiAnswers = new List<int>();

            foreach (Control ctl in questionPanel.Controls)
            {
                if (ctl.Name.StartsWith("answer"))
                {
                    CheckBox answerCheck = (CheckBox)ctl;
                    if (answerCheck.Checked)
                    {
                        checkboxName = answerCheck.Name;
                        multiAnswers.Add(int.Parse(checkboxName.Split('.')[2]));
                    }
                }
            }

            FillAnswerByQuestion(questionIndex, multiAnswers);
        }

        private void InitAnswers(bool isMultiOption)
        {
            RadioButton answerRadio = null;
            CheckBox answerCheckbox = null;
            Panel questionPanel = null;

            foreach (Control panel in this.splitContainer2.Panel2.Controls)
            {
                questionPanel = (Panel)panel;
                foreach (Control answer in questionPanel.Controls)
                {
                    if (answer.Name.StartsWith("answer") && answer.Name.EndsWith("0"))
                    {
                        if (!isMultiOption)
                        {
                            answerRadio = (RadioButton)answer;
                            answerRadio.Checked = false;
                            answerRadio.Checked = true;
                        }
                        else
                        {
                            answerCheckbox = (CheckBox)answer;
                            answerCheckbox.Checked = true;
                        }
                    }
                }
            }
        }

        private void DisplayAnswers(int surveyIndex)
        {
            XmlNode currentSurvey = Utility.RetrieveNodeByTagNameAndIndex(answersDocument, "questionnaire", --surveyIndex);           

            if (currentSurvey != null)
            {
                int countOfQuestions = Utility.RetrieveCountOfChildrenByName((XmlElement)currentSurvey, "question");
                string[] answers = new string[countOfQuestions];

                for (int questionIndex = 0; questionIndex < countOfQuestions; questionIndex++)
                {
                    XmlNode question = Utility.RetrieveNodeByTagNameAndIndex2((XmlElement)currentSurvey, "question", questionIndex);
                    string answerValue = question["answer"].InnerText.ToString();

                    if (string.IsNullOrEmpty(answerValue))
                    {
                        answerValue = "A";
                    }

                    answers[questionIndex] = answerValue;
                }

                this.splitContainer2.Panel2.Controls.Clear();
                ShowTilteAndIndex();
                InitializeCustomizeComponent(selectedQNIndex, answers);
            }
        }

        private void InitializeCustomizeComponent(int qnIndex, string[] answers)
        {
            int width = this.splitContainer2.Panel2.Width;
            int labelHeight = 20;
            int controlWidth = 200;
            int controlHeight = 20;
            int x = this.splitContainer2.Location.X;
            int y = this.splitContainer2.Location.Y;
            bool isLongText = false;

            System.Windows.Forms.Panel questionPanel = null;
            System.Windows.Forms.Label questionLabel = null;
            System.Windows.Forms.RadioButton answerRadio = null;
            System.Windows.Forms.CheckBox answerCheckbox = null;

            int questionDisplayIndex = 0;
            for (int i = 0; i < availableQNs[qnIndex].Questions.Count; i++)
            {
                int panelHeight = availableQNs[qnIndex].Questions[i].Height;
                if (availableQNs[qnIndex].Questions[i].Height > 60)
                {
                    isLongText = true;
                }
                else
                {
                    isLongText = false;
                }

                questionPanel = new System.Windows.Forms.Panel();
                questionPanel.SetBounds(x, y, width, panelHeight);
                
                questionPanel.Show();
                questionPanel.Name = "question.panel." + i.ToString();
                this.splitContainer2.Panel2.Controls.Add(questionPanel);

                questionLabel = new System.Windows.Forms.Label();
                questionLabel.SetBounds(0, 0, width, labelHeight); // default value of X, Y is 0
                questionLabel.Show();
                questionLabel.Name = "question." + i.ToString();
                if (availableQNs[qnIndex].Questions[i].QuestionRole != "Prerequisite")
                {
                    // It is a normal question.
                    questionDisplayIndex++;
                }
                else
                {
                    // It is not a normal question, do not count it in.
                }
                string questionTitle = (questionDisplayIndex == 0 ? "" : questionDisplayIndex.ToString() + ". ") + availableQNs[qnIndex].Questions[i].Title;
                questionLabel.Text = questionTitle;
                if (questionDisplayIndex == 0)
                {
                    questionLabel.Font = new Font(questionLabel.Font.FontFamily, questionLabel.Font.Size, FontStyle.Bold);
                }
                questionPanel.Controls.Add(questionLabel);

                string questionType = availableQNs[qnIndex].Questions[i].QuestionType.ToString();

                int controlY = 30;
                if (string.Equals(questionType, "SingleChoice"))
                {
                    int controlX = 0;
                    int count = availableQNs[qnIndex].Questions[i].AvailableAnswers.Count;
                    for (int index = 0; index < count; index++)
                    {
                        answerRadio = new System.Windows.Forms.RadioButton();
                        answerRadio.Show();
                        answerRadio.Name = "answer." + i.ToString() + "." + index.ToString();
                        answerRadio.Text = availableQNs[qnIndex].Questions[i].AvailableAnswers[index].FullText.ToString();

                        if (isLongText)
                        {
                            controlWidth = this.splitContainer2.Width;
                            controlX = 0;
                        }

                        answerRadio.SetBounds(controlX, controlY, controlWidth, controlHeight);

                        if (answers != null)
                        {
                            if (answerRadio.Text.StartsWith(answers[i]))
                            {
                                answerRadio.Checked = true;
                            }
                        }
                        else
                        {
                            if (index == 0)
                            {
                                answerRadio.Checked = true;
                            }
                        }

                        answerRadio.CheckedChanged += new System.EventHandler(answerRadio_CheckedChanged);
                        answerRadio.GotFocus += new EventHandler(answerRadio_GotFocus);
                        questionPanel.Controls.Add(answerRadio);

                        if (isLongText)
                        {
                            controlY += 30;
                        }
                        else
                        {
                            controlX += 200;
                        }
                    }
                }
                else if (string.Equals(questionType, "MultipleChoices"))
                {
                    int controlX = 0;
                    int count = availableQNs[qnIndex].Questions[i].AvailableAnswers.Count;
                    for (int index = 0; index < count; index++)
                    {
                        answerCheckbox = new System.Windows.Forms.CheckBox();
                        answerCheckbox.Show();
                        answerCheckbox.Name = "answer." + i.ToString() + "." + index.ToString();
                        answerCheckbox.Text = availableQNs[qnIndex].Questions[i].AvailableAnswers[index].FullText.ToString();

                        if (isLongText)
                        {
                            controlWidth = this.splitContainer2.Width - 100;
                            controlX = 0;
                        }

                        answerCheckbox.SetBounds(controlX, controlY, controlWidth, controlHeight);

                        if (answers != null)
                        {
                            if (answers[i].Length >= 1)
                            {
                                string[] answerArray = answers[i].Split(',');

                                foreach (string answer in answerArray)
                                {
                                    if (answerCheckbox.Text.StartsWith(answer))
                                    {
                                        answerCheckbox.Checked = true;
                                    }
                                }
                            }
                        }
                        else
                        {
                            if (index == 0)
                            {
                                answerCheckbox.Checked = true;
                            }
                        }

                        answerCheckbox.CheckedChanged += new System.EventHandler(answerCheckbox_CheckedChanged);
                        answerCheckbox.GotFocus += new EventHandler(answerCheckbox_GotFocus);
                        questionPanel.Controls.Add(answerCheckbox);

                        if (isLongText)
                        {
                            controlY += 30;
                        }
                        else
                        {
                            controlX += 150;

                            if (index == 5)
                            {
                                controlY += 25;
                                controlX = 0;
                            }
                        }
                    }

                    controlY -= 25;
                }
                else
                {
                    // Nothing to do...
                }

                x = this.splitContainer2.Location.X;
                int height = panelHeight;
                y += height;
            }
            PaintPanelBackColor();
        }

        

        private void PaintPanelBackColor()
        {
            for (int i = 0; i < splitContainer2.Panel2.Controls.Count; i++)
            {
                Panel questionPanel = (Panel)splitContainer2.Panel2.Controls[i];
                if (i % 2 == 0)
                    questionPanel.BackColor = Color.FromArgb(235, 235, 235);
                else
                    questionPanel.BackColor = Color.Transparent;
            }
        }
        Panel respondingPanel = null;
        private void answerRadio_GotFocus(object sender, EventArgs e)
        {
            PaintPanelBackColor();
            respondingPanel = (Panel)((Control)sender).Parent;
            if (respondingPanel != null)
                respondingPanel.BackColor = Color.Bisque;
        }
        private void answerCheckbox_GotFocus(object sender, EventArgs e)
        {
            PaintPanelBackColor();
            respondingPanel = (Panel)((Control)sender).Parent;
            if (respondingPanel != null)
                respondingPanel.BackColor = Color.Bisque;
        }
        private void PrevQNToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Previous_Click(sender, e);
        }

        private void NextQNToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Next_Click(sender, e);
        }

        private void AboutToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            MessageBox.Show("当前版本 " + System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString(), "关于");
        }
    }
}
